package server;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.Charset;
import java.util.LinkedList;
import java.util.List;

/**
 * A Bridge-Http Server
 * 
 * @author Alessandro Martinelli
 */
public class HTTPServer {
	
	private int port;
	private IHTTPServer server;

	public HTTPServer(int port, IHTTPServer server) {
		super();
		this.port = port;
		this.server = server;
	}


	/**
	 * lancia questo server che potrà rispondere alle richieste HTTP
	 */
	public void launch() {
		
		ServerSocket socket=null;
		
		try {
			socket=new ServerSocket(port);
		
			while(true){
			
				Socket clientSocket = socket.accept();
			
				System.err.println("Client Socket Accepted!!"+clientSocket.getInetAddress()+" "+clientSocket.getLocalPort());
				
				BufferedReader in = new BufferedReader(
				    new InputStreamReader(clientSocket.getInputStream()));
			    String line=in.readLine();
			    
			    LinkedList<String> richiestaHTTP=new LinkedList<String>();
			    while(line!=null){
			    	richiestaHTTP.add(line);
		    		
			    	line=in.readLine();
			    	if(line.length()==0){
			    		line=null;
			    	}
			    }
			    /*
			     * Se la richiesta deve scrivere byte -> scrive su outpuStream e risposta è vuoto
			     * Se risposta contiene qualcosa (gli altri servizi diversi dalla richiesta file)
				 * allora la risposta viene stampata correttamente
			     */
			    DataOutputStream outputStream = new DataOutputStream(clientSocket.getOutputStream());
			    List<String> risposta=server.elaboraRispostaHTTP(richiestaHTTP, outputStream);
			    if (!risposta.isEmpty()) {
			    	OutputStreamWriter out = new OutputStreamWriter(
							clientSocket.getOutputStream(),
						     Charset.forName("UTF-8").newEncoder() 
						 );
					
					for (String string : risposta) {
						out.write(string+"\n");
					}
					out.close();
				}
				outputStream.close();

				clientSocket.close();
			}
				    
		} catch (IOException e) {
			e.printStackTrace();
		}
		//chiudere il socket prima di terminare!!
		try {
			if(socket!=null)
				socket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
